//
//  ViewController.swift
//  Game
//
//  Created by 勇胡 on 2025/8/19.
//

import UIKit

class ViewController: UIViewController {
    
    private var dataArray:[GameModel] = []
    private var tableView:UITableView!
    var iconList:[String] = ["fan.badge.automatic","lizard","gamecontroller","puzzlepiece","dice","brain.head.profile","trophy","sun.max","flag.2.crossed","figure.walk.circle","airplane.circle","bolt.car","figure.roll","xbox.logo","personalhotspot.circle","chart.bar","bonjour","fan.badge.automatic",]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        iconList = iconList.shuffled()
        createUI()
        refresh()
    }
    
    private func refresh(){
        dataArray = GameManager.share.getAllGames_reversed(type: nil)
        tableView.reloadData()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = false
        self.navigationController?.isNavigationBarHidden = false
    }
    private func createUI(){
        // 设置导航栏
        navigationItem.title = "游戏"
        
        //添加按钮
        let addItem = UIBarButtonItem(image: UIImage(systemName: "document.badge.plus"), style: .plain, target: self, action: #selector(onAdd))
        addItem.tintColor = .white
        navigationItem.rightBarButtonItem = addItem
        
        //设置
        let settingItem = UIBarButtonItem(image: UIImage(systemName: "gearshape"), style: .plain, target: self, action: #selector(onSetting))
        settingItem.tintColor = .white
        navigationItem.leftBarButtonItem = settingItem
        
        tableView = UITableView(frame:.zero, style: .plain)
        tableView.backgroundColor = Colors.bgColor
        tableView.estimatedRowHeight = UITableView.automaticDimension
        tableView.estimatedSectionFooterHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .singleLine
        tableView.separatorColor = Colors.line2
        tableView.separatorInset = .zero
        tableView.separatorStyle = .none
        tableView.keyboardDismissMode = .onDrag
        tableView.register(GameListCell.self, forCellReuseIdentifier:"GameListCell")
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .automatic
        }
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    @objc func onAdd(){
        //先选择类型，再根据类型配置页面
        let typeAlert = SingleTablePicker(frame: .zero)
        let dataArray:[GameType] = GameType.allTypes()
        let titles:[String] = dataArray.map{$0.rawValue}
        
        typeAlert.onSelectedRowBlock = {[weak self](index,val)in
            guard let `self` = self else { return }
            let gameType = dataArray[index]
            //句子
            if gameType == .sentence{
                let vc = SentenceVC()
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
                
            //查找
            }else if gameType == .findWord{
                let vc = WordsConfigVC()
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
             
            //句子找答案句子
            }else if gameType == .sentenceAnswerSentence{
                let vc = SentenceToSenConfigVC()
                vc.gameModel = GameModel.defaultSentenceToSModel()
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
             
            //消消乐
            }else if gameType == .weedOut{
                let vc = WordsConfigVC()
                vc.gameModel = GameModel.defaultWeedOut()
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
                
            //毒药
            }else if gameType == .poison{
                let vc = WordsConfigVC()
                vc.gameModel = GameModel.defaultPosion()
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
                
            }else{//卡片
                let settingAlert = SettingAlertView(frame: .zero)
                let game = GameModel.defaultModel()
                game.type = dataArray[index].rawValue
                settingAlert.onSubmitBlock = {[weak self] in
                    guard let `self` = self else { return }
                    self.refresh()
                }
                settingAlert.show(vc: self, game: game)
            }
        }
        typeAlert.show(dataArray: titles, pickerW: 400)
        
        
        
    }
    
    //设置
    @objc func onSetting(){
        let alert = UIAlertController(title: "设置音效", message:"是否启用音效", preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "启用", style: .default,handler: { action in
            Utils.isEnableSound = true
        }))
        alert.addAction(UIAlertAction(title: "禁用", style: .destructive,handler: { action in
            Utils.isEnableSound = false
        }))
        alert.addAction(UIAlertAction(title: "测试代码", style: .destructive,handler: { action in
            MyNavigator.push(TestVC())
        }))
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        if let pop = alert.popoverPresentationController {
            pop.barButtonItem = navigationItem.leftBarButtonItem
            if pop.barButtonItem == nil {
                pop.sourceView = self.view
                pop.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 1, height: 1)
            }
            pop.permittedArrowDirections = .any
        }
        present(alert, animated: true)

    }
}

extension ViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier:"GameListCell", for: indexPath) as! GameListCell
        let item = dataArray[indexPath.row]
        let indexIcon = indexPath.row % self.iconList.count
        let icon = iconList[indexIcon]
        cell.updateBy(model: item, icon:icon ,index: indexPath.row)
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        
        return UITableViewCell.EditingStyle.delete
    }
    
    //点击删除按钮的响应方法，在这里处理删除的逻辑
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        print("点击删除")
        
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let item = dataArray[indexPath.row]
        
        let deleteAction = UIContextualAction(style: .destructive, title: "删除") { [weak self] (action, view, completionHandler) in
            guard let self = self else { return }
            
            print("删除\(item.key)")
            GameManager.share.delete(gameKey: item.key)
            self.dataArray.remove(at: indexPath.row)
            self.tableView.reloadData()
            completionHandler(true)
        }
        deleteAction.image = UIImage(systemName: "trash")
        
        let editAction = UIContextualAction(style: .normal, title: "编辑") { [weak self] (action, view, completionHandler) in
            guard let self = self else { return }
            print("编辑")
            if item.type == GameType.sentence.rawValue{
                let vc = SentenceVC()
                vc.gameModel = item
                MyNavigator.push(vc)
                
            }else if item.type == GameType.findWord.rawValue{
                let vc = WordsConfigVC()
                vc.gameModel = item
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
                
            }else if item.type == GameType.sentenceAnswerSentence.rawValue{
                let vc = SentenceToSenConfigVC()
                vc.gameModel = item
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
             
            }else if item.type == GameType.weedOut.rawValue{
                let vc = WordsConfigVC()
                vc.gameModel = item
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
                
            }else if item.type == GameType.poison.rawValue{
                let vc = WordsConfigVC()
                vc.gameModel = item
                vc.onSubmitBlock = {[weak self]in
                    self?.refresh()
                }
                MyNavigator.push(vc)
                
            }else{
                let alert = SettingAlertView(frame: .zero)
                alert.onSubmitBlock = {[weak self] in
                    guard let `self` = self else { return }
                    self.refresh()
                }
                alert.show(vc: self, game: item)
            }
            completionHandler(true)
        }
        editAction.backgroundColor = .systemBlue
        editAction.image = UIImage(systemName: "pencil")
        
        let configuration = UISwipeActionsConfiguration(actions: [deleteAction, editAction])
        configuration.performsFirstActionWithFullSwipe = false
        return configuration
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = dataArray[indexPath.row]
        guard let type = GameType(rawValue: item.type) else {return}
        
        // 确保有导航控制器
        guard let navController = self.navigationController else {
            print("导航控制器未设置")
            return
        }
        
        switch type {
        case .color:
            let vc = PlayColorVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        case .expression:
            let vc = ExpressionVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        case .expression2:
            let vc = Expression2VC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        case .sentence:
            let vc = SentencePlayVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        case .findWord:
            let vc = FindWordPlayVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        case .ligature:
            let vc = LigaturePlayVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        case .dragAndDropToFill:
            let vc = DrapWordPlayVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        case .sentenceAnswerSentence:
            let vc = SentenceToSenPlayVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        case .weedOut:
            let vc = WeedOutPlayVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
        
        case .poison:
            let vc = PoisonPlayVC()
            vc.gameModel = item
            navController.pushViewController(vc, animated: true)
            
        default:
            break
        }
    }
}
